#!/usr/bin/python3
# 2016.11.18 尝试搞GUI
# -*- coding:utf-8 -*-


import datetime
import threading
import tkinter
import tkinter.filedialog
from tkinter import messagebox
import Find_ceRNA
import mirandaFile
import re


# 重载的多线程
class forTkinter(threading.Thread):
    def __init__(self, file, outdir, thread, which):
        threading.Thread.__init__(self)
        self.file = file
        self.outdir = outdir
        self.thread = thread
        self.which = which

    def run(self):
        if self.which == 1:
            mirandaFile.extract_miranda(inputFile=self.file, outputFile=self.outdir,
                                        thread=self.thread)
        else:
            Find_ceRNA.cerna_pairs(input_file=self.file, output_file=self.outdir, thread=self.thread)


def shuoming():
    messagebox.showinfo('说明', '用来计算ceRNA对\n可以直接使用miranda的输出文件\n但是功能比较差劲，只能一个文件目前\n自己提取的两列文件')


def about():
    messagebox.showinfo('关于', '学习Python练手的第二个GUI程序\n\t张一鸣\t\n\t于2016.11.19')


def main():
    # 用来给界面上的按钮赋值的
    def openFile():  # 打开文件
        r = tkinter.filedialog.askopenfilename(title="输入文件", filetypes=[('文本文件', '.txt'), ('All files', '*')])
        infile.set(str(r))
        return r

    # asksavedirectory asksavefilename 指定保存的目录或者文件
    def FileSave():  # 设置保存目录
        r = tkinter.filedialog.asksaveasfilename(title="输出目录")
        outdir.set(r)
        return r

    def getthread():  # 用来返回进程数
        num = thread.get()
        if not num or num <= 0:
            num = 1
        return num

    def show_message():
        if checked.get() == 1:
            text.set('请输入miranda的输出结果')
        else:
            if text.get() == '请输入miranda的输出结果':
                text.set('请输入两列的RNA结合关系文件')
                checked.set(0)

    def run_command():
        thread = getthread()
        which = checked.get()
        input_file = infile.get()
        output_file = outdir.get()

        begin = datetime.datetime.now()
        if not infile.get() and not outdir.get():
            messagebox.showinfo('错误', '没有任何输入')
        elif not infile.get() and outdir.get():
            messagebox.showinfo('错误', '没有输入文件')
        elif infile.get() and not outdir.get():
            messagebox.showinfo('错误', '没有输出文件夹')
        else:
            if which == 1:
                pattern = re.compile('\\.')
                test1 = pattern.search(output_file)
                output_tem = output_file[:test1.end()] + 'miranda'
                messagebox.showinfo('miranda提取结果保存为', output_tem)
                t = forTkinter(file=input_file, outdir=output_tem, thread=thread, which=1)
                t.start()
                runButton.config(text='等着吧', stat=tkinter.DISABLED)
                t.join()
                input_file = output_tem
                messagebox.showinfo('进度', 'miranda提取结果完成')
            t = forTkinter(file=input_file, outdir=output_file, thread=thread, which=0)
            t.start()
            runButton.config(text='等着吧', stat=tkinter.DISABLED)
            t.join()
            end = datetime.datetime.now()
            runtime = str(end - begin)
            messagebox.showinfo('已完成', "共计运行" + runtime)
            runButton.config(text='开始', stat=tkinter.NORMAL)

    def wait():
        evt.clear()
        keepButton.config(stat=tkinter.NORMAL)
        waitButton.config(stat=tkinter.DISABLED)

    def conti():
        evt.set()
        keepButton.config(stat=tkinter.DISABLED)
        waitButton.config(stat=tkinter.NORMAL)

    root = tkinter.Tk()
    # 主窗口的设置
    root.title("计算ceRNA对，这么用结果不好说;)))))")
    root.geometry("800x500+200+200")
    root.resizable(width=False, height=False)

    # 初始化变量，各种所需的变量
    text = tkinter.StringVar()
    text.set('')
    infile = tkinter.StringVar()
    outdir = tkinter.StringVar()
    checked = tkinter.IntVar()
    checked.set(0)
    thread = tkinter.IntVar()
    thread.set(1)
    evt = threading.Event()

    # 添加菜单，菜单大同小异，就这样了
    menu = tkinter.Menu(root)
    submenu = tkinter.Menu(menu, tearoff=0)
    submenu.add_command(label="打开", command=openFile, accelerator='Ctrl+N')
    submenu.add_command(label="保存", command=FileSave)
    submenu.add_separator()  # 添加分隔线
    submenu.add_command(label="退出", command=root.quit)
    menu.add_cascade(label="文件", menu=submenu)
    submenu = tkinter.Menu(menu, tearoff=0)  # 新建子菜单
    submenu.add_command(label="说明", command=shuoming)
    submenu.add_command(label="关于", command=about)
    menu.add_cascade(label="帮助", menu=submenu)
    root.config(menu=menu)  # 在窗口中设置菜单
    # 添加输入框
    inputL = tkinter.Label(root, text="输入文件")
    inputL.place(x=50, y=80,
                 width=150, height=30)
    inputE = tkinter.Entry(root, textvariable=infile)
    inputE.place(x=250, y=80,
                 width=300, height=30)
    inputB = tkinter.Button(root, text="打开", command=openFile)
    inputB.place(x=600, y=80,
                 width=60, height=30)
    # 输出文件的各种框
    outputL = tkinter.Label(root, text="输出文件")
    outputL.place(x=50, y=130,
                  width=150, height=30)
    outputE = tkinter.Entry(root, textvariable=outdir)
    outputE.place(x=250, y=130,
                  width=300, height=30)
    outputB = tkinter.Button(root, text="输出", command=FileSave)
    outputB.place(x=600, y=130,
                  width=60, height=30)

    # 进程数
    threadL = tkinter.Label(root, text="进程数：")
    threadL.place(x=400, y=180,
                  width=50, height=30)

    threadE = tkinter.Entry(root, textvariable=thread)
    threadE.place(x=500, y=180,
                  width=100, height=30)

    # 添加一个run按钮
    runButton = tkinter.Button(root, text="运行", command=run_command)
    runButton.place(relx=0.7, y=230,
                    width=100, height=50)

    # 添加一个暂停按钮
    waitButton = tkinter.Button(root, text="暂停", stat=tkinter.DISABLED, command=wait)
    waitButton.place(relx=0.4, y=230,
                     width=100, height=50)

    # 添加一个继续按钮
    keepButton = tkinter.Button(root, text="继续", stat=tkinter.DISABLED, command=conti)
    keepButton.place(relx=0.1, y=230,
                     width=100, height=50)

    # 添加一个checkbox
    c = tkinter.Checkbutton(root, text='miranda?', variable=checked, command=show_message)
    c.place(relx=0.1, y=300)
    # 添加一个文本框，显示，复选框的状态
    entry_c = tkinter.Entry(root, textvariable=text)
    entry_c.place(relx=0.4, y=300, width=300)

    # 添加一个图形
    image = tkinter.Canvas(root, width=400, height=250)
    image.create_text(250, 50, text='复选框用来标明\n是否用miranda程序输出文件\nPS:如果遇到无法输出文件\n请反复勾选一下复选框', fill='red', font=("宋体", 15, "normal"))
    image.place(relx=0.2, y=330)

    # 动作绑定
    root.bind_all("<Control-n>", lambda event: openFile())

    # 添加一个text窗口
    root.mainloop()

if __name__ == '__main__':
    main()
